<template>
  <div class="uploadImg">
        <label :for="'uploadImg'+ site" class="uploadImgBtn">
            <!-- {{title}}  -->
            <input type="file" @change="upload($event)" :id="'uploadImg'+ site"> 
        </label>
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },
  props: {
    title: {
      type: String
    },
    site: {
      type: Number
    },
    filePath: {
      type: String,
      required: true
    }
  },
  methods: {
    randomString(len) {
      len = len || 32;
      let chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
      let maxPos = chars.length;
      let pwd = "";
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
      }
      return pwd;
    },
    async upload(e) {
      let self = this;
      let files = e.target.files[0];
      let res = await this.$get({
        url: self.fn.chatApi + "/admin/upload/getWebUpLoadSign"
      });
      if (res.code === 111111) {
        let datas = res.data;
        let host = datas.host;
        let Param = new FormData(); // 创建form对象
        let randomNum = self.randomString(10)
        let url = datas.dir + randomNum + "." + files.type.split("/")[1]
        Param.append(
          "key",
          datas.dir + randomNum + "." + files.type.split("/")[1]
        );
        Param.append("policy", datas.policy);
        Param.append("OSSAccessKeyId", datas.accessId);
        // Param.append("callback", datas.callback);
        Param.append("success_action_status", "200");
        Param.append("signature", datas.signature);
        Param.append("file", files); // 通过append向form对象添加数据
        self.uploadImg(host, Param,url);
      }
    },
    async uploadImg(host, Param,url) {
      let self = this;
      await this.$post({
        url: host,
        data: Param
      }).then(res => {
         self.$emit('imgUrl',host+'/'+ url)
      });

     
    }
  }
};
</script>


<style lang="scss" scoped>
.uploadImg {
  display: inline-block;
  position: relative;
}
input[id^="uploadImg"] {
  display: none;
}
.uploadImgBtn {
  position: absolute;
  left: 0;
  top: 0;
  display: inline-block;
  line-height: 1;
  white-space: nowrap;
  cursor: pointer;
  // background: #fff;
  // border: 1px solid #d8dce5;
  color: #5a5e66;
  -webkit-appearance: none;
  text-align: center;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  outline: 0;
  margin: 0;
  -webkit-transition: 0.1s;
  transition: 0.1s;
  font-weight: 500;
  padding:35.5px;
  width: 100%;
  height: 100%;
  font-size: 14px;
  // border-radius: 4px;
  // color: #fff;
  // background-color: #409EFF;
  // border-color: #409EFF;
}
</style>
